<template>
  <basic-container>
    <!--      @current-change="currentChange"
                   @size-change="sizeChange" -->
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoad"
    >
      <template slot="menuLeft">
        <!-- <el-button type="primary"
                           size="small"
                           icon="el-icon-plus"
                           @click="addBtn">新增</el-button> -->
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.organization_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" icon="el-icon-circle-plus-outline" size="small" @click.stop="handleAdd(scope.row, scope.index)"
          >新增子项
          <!-- v-if=" scope.row.category === 1" -->
        </el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getMenuTreeOrg, getLazyList } from '@/api/admin/organization';
import { mapGetters } from 'vuex';

import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      form: {},
      query: {},
      tableOption: {},
      loading: true,
      isShowDialog: false,
      parentId: 0,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        lazy: true, // 懒加载
        height: 'auto', // 高度自适应
        calcHeight: 30, //表格高度差（主要用于减去其他部分让表格高度自适应）
        tip: false,
        minWidth: 'auto', //列最小宽度
        tree: true,
        searchShow: true,
        searchSpan: 7,
        searchMenuSpan: 6,
        border: true,
        // addBtn: false,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        labelWidth: '140',
        column: [
          {
            label: '统一社会信用代码',
            prop: 'socialCreditCode',
            rules: [
              {
                required: true,
                message: '请输入统一社会信用代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '企业类型',
            prop: 'orgType',
            rules: [
              {
                required: true,
                message: '请输入企业类型',
                trigger: 'blur'
              }
            ]
          },
          // {
          //     label: "ERP主键",
          //     prop: "erpKey",
          //     rules: [{
          //         required: false,
          //         message: "请输入erp主键",
          //         trigger: "blur"
          //     }]
          // },
          {
            label: '组织名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入组织名称',
                trigger: 'blur'
              }
            ]
          },
          // {
          //     label: "地址",
          //     prop: "locationId",
          //     rules: [{
          //         required: true,
          //         message: "请输入地址",
          //         trigger: "blur"
          //     }]
          // },
          {
            label: '法人',
            prop: 'principalName',
            disabled: true,
            type: 'search',
            appendClick: () => {
              this.openCommonModal();
            }
          },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [
              {
                required: false,
                message: '请输入联系方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '注册号',
            prop: 'registrationNumber',
            rules: [
              {
                required: true,
                message: '请输入注册号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '注册日期',
            prop: 'registerDate',
            search: true,
            type: 'date',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            rules: [
              {
                required: true,
                message: '请输入注册日期',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '上一级组织',
            prop: 'parentId',
            type: 'tree',
            dicData: [], // 初始化字典信息，不然数据动态展示不了
            // dicUrl: "/api/blade-system/dict/dictionary-tree?code=ORGNIZE_TYPE",
            display: false,
            hide: true,
            addDisabled: false,
            value: 0,
            props: {
              // 子集菜单显示
              label: 'dictValue',
              value: 'dictValue'
            },
            rules: [
              {
                required: false,
                message: '请输入上一级组织',
                trigger: 'click'
              }
            ]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.organization_add, false),
        viewBtn: this.vaildData(this.permission.organization_view, false),
        delBtn: this.vaildData(this.permission.organization_delete, false),
        editBtn: this.vaildData(this.permission.organization_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    /**
     * 打开模态框
     */
    openCommonModal() {
      this.modalName = 'paramsModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },

    getSelectedRows(rows) {
      this.form['principalName'] = rows.name;
      this.form['principal'] = rows.id;
    },

    // addBtn() {
    //     this.title = '新增';
    //     this.isShowDialog = true;
    // },

    initData() {
      getMenuTreeOrg().then((res) => {
        const column = this.findObject(this.option.column, 'parentId');
        column.dicData = res.data.data;
      });
    },
    handleAdd(row) {
      this.parentId = row.id;
      const column = this.findObject(this.option.column, 'parentId');
      column.value = row.id;
      column.addDisabled = true;
      this.$refs.crud.rowAdd();
    },
    rowSave(row, done, loading) {
      console.log(row);
      add(row).then(
        (res) => {
          // 获取新增数据的相关字段
          const data = res.data.data;
          row.id = data.id;
          // this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done(row);
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          // this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done(row);
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done(row);
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      // if (["add", "edit"].includes(type)) {
      //     this.initData();
      // }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    beforeClose(done) {
      this.parentId = '';
      const column = this.findObject(this.option.column, 'parentId');
      column.value = 0;
      column.addDisabled = false;
      done();
    },
    searchReset() {
      this.query = {};
      this.parentId = 0;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.parentId = '';
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      // page.pageSize,page.currentPage,
      getLazyList(this.parentId, Object.assign(params, this.query)).then((res) => {
        this.data = res.data.data;
        // this.page.total = data.total;
        this.loading = false;
        this.selectionClear();
      });
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      getLazyList(parentId).then((res) => {
        resolve(res.data.data);
      });
    }
  }
};
</script>

<style></style>
